package com.gxy.learn.backup.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.List;

/**
 * text文档工具类
 */

public class FileUtils {
    private static final Logger log = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 写入txt文件
     *
     * @param result   文件内容
     * @param fileName 文件名称
     * @param filePath 文件路径
     * @return
     */
    public static boolean writeFile(List<String> result, String fileName, String filePath) {
        BufferedWriter out = null;
        try {
            if (CollectionUtils.isEmpty(result) || StringUtils.isAnyBlank(fileName, filePath)) {
                log.error("写入数据失败！result = {},fileName = {}，filePath = {}", JSONObject.toJSON(result), fileName, fileName);
                return false;
            }
            File pathFile = new File(filePath);
            if (!pathFile.exists()) {
                pathFile.mkdir();
            }
            String relFilePath = null;
            if (filePath.endsWith(File.separator)) {
                relFilePath = filePath + fileName;
            } else {
                relFilePath = filePath + File.separator + fileName;
            }
            log.info("relFilePath = {}", relFilePath);
            File file = new File(relFilePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "GBK"));
            //                //标题头
            //                out.write("curr_time,link_id,travel_time,speed,reliabilitycode,link_len,adcode,time_stamp,state,public_rec_time,ds");
            //                out.newLine();
            for (String info : result) {
                out.write(info);
                out.newLine();
            }
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            IOUtils.close(out);
        }
    }
}
